package com.zyb.lmbackend.schedule;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zyb.lmbackend.entity.CategoryDict;
import com.zyb.lmbackend.entity.GoodsBack;
import com.zyb.lmbackend.llm.LlmClient;
import com.zyb.lmbackend.llm.model.ClsResult;
import com.zyb.lmbackend.mapper.ClassifyTaskMapper;
import com.zyb.lmbackend.mapper.GoodsBackClassifiedMapper;
import com.zyb.lmbackend.mapper.GoodsBackMapper;
import com.zyb.lmbackend.service.CategoryDictService;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * 增量分类定时任务：
 * 每小时扫描最新版本中尚未分类的数据，调用 LLM 批量分类并写入结果。
 */
@Component
@RequiredArgsConstructor
@Slf4j
public class IncrementalClassifierJob {

    private final GoodsBackMapper goodsBackMapper;
    private final GoodsBackClassifiedMapper classifiedMapper;
    private final CategoryDictService categoryDictService;
    private final LlmClient llmClient;
    private final ClassifyTaskMapper classifyTaskMapper;

    /** 每小时执行一次增量分类。 */
    @Scheduled(cron = "0 0 * * * ?")
    public void runHourly() {
        int latest = Math.max(1, classifyTaskMapper.selectMaxVersion());
        List<GoodsBack> list = goodsBackMapper.selectUnclassified(latest, 500);
        if (list.isEmpty()) return;
        List<String> allowed = categoryDictService.list(new LambdaQueryWrapper<CategoryDict>().eq(CategoryDict::getIsActive, (byte) 1))
                .stream().map(CategoryDict::getCode).collect(Collectors.toList());
        List<String> details = list.stream().map(GoodsBack::getBackDetail).collect(Collectors.toList());
        List<ClsResult> results = new ArrayList<>();
        try {
            results = llmClient.classifyBatch(details, allowed);
        } catch (Exception e) {
            log.warn("Incremental classify failed, will skip this run", e);
            return;
        }
        for (int i = 0; i < results.size() && i < list.size(); i++) {
            ClsResult r = results.get(i);
            GoodsBack g = list.get(i);
            classifiedMapper.upsert(g.getSn(), g.getBackDetail(), r.getCategoryCode(), r.getConfidence(), r.getReason(), "dashscope", latest);
        }
    }
}
